🌳 radix3
Lightweight and fast router for JavaScript based on Radix Tree.
Usage
Install package:
npm i radix3
yarn add radix3
pnpm i radix3
Import:
import { createRouter } from "radix3";
const { createRouter } = require("radix3");
Create a router instance and insert routes:
const router = createRouter();
router.insert("/path", { payload: "this path" });
router.insert("/path/:name", { payload: "named route" });
router.insert("/path/foo/**", { payload: "wildcard route" });
router.insert("/path/foo/**:name", { payload: "named wildcard route" });
Match route to access matched data:
router.lookup("/path");
router.lookup("/path/fooval");
router.lookup("/path/foo/bar/baz");
router.lookup("/");
Methods
router.insert(path, data)
path
can be static or using :placeholder
or **
for wildcard paths.
The data
object will be returned on matching params. It should be an object like { handler }
and not containing reserved keyword params
.
router.lookup(path)
Returns matched data for path
with optional params
key if mached route using placeholders.
router.remove(path)
Remove route matching path
.
Options
You can initialize router instance with options:
const router = createRouter({
strictTrailingSlash: true,
routes: {
"/foo": {},
},
});
routes
: An object specifying initial routes to addstrictTrailingSlash
: By default router ignored trailing slash for matching and adding routes. When set to true
, matching with trailing slash is different.
Route Matcher
Creates a multi matcher from router tree that can match all routes matching path:
import { createRouter, toRouteMatcher } from "radix3";
const router = createRouter({
routes: {
"/foo": { m: "foo" },
"/foo/**": { m: "foo/**" },
"/foo/bar": { m: "foo/bar" },
"/foo/bar/baz": { m: "foo/bar/baz" },
"/foo/*/baz": { m: "foo/*/baz" },
},
});
const matcher = toRouteMatcher(router);
const matches = matcher.matchAll("/foo/bar/baz");
Route Matcher Export
It is also possible to export and then rehydrate a matcher from pre-compiled rules.
import { exportMatcher, createMatcherFromExport } from "radix3";
const json = exportMatcher(matcher);
const newMatcher = createMatcherFromExport(json);
const matches = newMatcher.matchAll("/foo/bar/baz");
Performance
See benchmark.
License
Based on original work of charlieduong94/radix-router
by Charlie Duong (MIT)
MIT - Made with ❤️